<?php
/**
 * File Model
 *
 * @author      Hyper <hyper@flashbay.com>
 * @copyright   Copyright (c) 2011 (http://www.saleshero.com)
 */
class Application_Model_File extends SalesHero_Model_Abstract
{

    /**
     * File path
     *
     * @var string
     */
    public $fileBasePath = null;

    public function __construct()
    {
        parent::__construct();
        $this->setBasePath($this->config->upload->basePath);
    }

    /**
     * Set base path
     *
     * @param  string $path
     * @return object
     */
    public function setBasePath($path = '')
    {
        $this->fileBasePath = $path;
        return $this;
    }

    /**
     * Delete a file
     *
     * @param int $id
     */
    public function delete($id)
    {
        if ($id <= 0) {
            throw new Exception('You should specify a file');
        }

        $info = $this->getInfo($id);
        $abspath = WEB_DIR . $info['path'];
        @unlink($abspath);

        $where = $this->db->quoteInto('file_id = ?', $id);
        $this->db->delete('file', $where);
    }

    /**
     * Get file info
     *
     * @param  int $id
     * @return array
     */
    public function getInfo($id)
    {
        $select = $this->db->select()->from('file')->where('file_id = ?', $id);
        return $this->db->fetchRow($select);
    }

    /**
     * Update file info
     *
     * @param array $params
     */
    public function update($params)
    {
        if (isset($params['folder_id']) && $params['folder_id'] >= 0) {
            $data['folder_id'] = $params['folder_id'];
        }
        if (isset($params['filename'])) {
            $params['filename'] = trim($params['filename']);
            if (strlen($params['filename']) < 3) {
                throw new Exception("Filename's length should be greater than 3");
            }
            if (strlen($params['filename']) > 40) {
                throw new Exception("Filename's length should be less than 40");
            }
            $data['filename'] = $params['filename'];
        }
        isset($params['description']) && $data['description'] = trim($params['description']);

        $data['modified'] = date('Y-m-d H:i:s');

        if ($params['id'] <= 0) {
            throw new Exception('You should specify a file');
        }
        $where = $this->db->quoteInto('file_id = ?', $params['id']);
        $this->db->update('file', $data, $where);
    }

    /**
     * Upload file and return file info
     *
     * @param  int      $folderId
     * @param  array    $data
     * @param  string   $subDir
     * @return array
     */
    public function upload($folderId, array $data, $subDir = 'cabinet')
    {
        $select = $this->db->select()->from('file_folder')->where('folder_id = ?', $folderId);
        $folderInfo = $this->db->fetchRow($select);
        if (empty($folderInfo)) {
            throw new Exception('The folder does not exist');
        }

        $savePath = $this->fileBasePath . "/$subDir/" . date('ym');
        $upload = new SalesHero_File(array('savePath' => $savePath));

        $result = $upload->save($data);
        $result['folder_id'] = $folderId;

        return $result;
    }

    /**
     * Add file info into database
     *
     * @param  array    $info
     * @return int      The file id
     */
    public function add(array $info)
    {
        if (!isset($info['filename']) || !isset($info['path'])) {
            throw new Exception('Invalid file info');
        }

        $data = array(
            'folder_id'     => $info['folder_id'],
            'created'       => date('Y-m-d H:i:s'),
            'modified'      => date('Y-m-d H:i:s'),
            'description'   => htmlspecialchars(trim(@$info['description'])),
            'filename'      => $info['filename'],
            'filesize'      => $info['filesize'],
            'filetype'      => $info['filetype'],
            'extension'     => $info['extension'],
            'path'          => str_replace(array(WEB_DIR, '\\'), array('', '/'), $info['path']),
        );

        $this->db->insert('file', $data);
        return $this->db->lastInsertId();
    }

}